<template>
  <div class="Award">
    <el-button-group>
      <el-button id="button" @click="dialog = true">
        上传奖状<i class="el-icon-upload el-icon--right"></i>
      </el-button>
    </el-button-group>

    <el-table :data="tableData" height="900" :row-style="{ height: '50px' }">
      <el-table-column label="奖状图片" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.awardUrl"
            fit="fit"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="awardName" label="奖项名称">
      </el-table-column>
      <el-table-column align="center" prop="levelName" label="奖项等级">
      </el-table-column>
      <el-table-column align="center" prop="awardTime" label="获奖时间">
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="上传时间">
      </el-table-column>
      <el-table-column align="center" label="上传人" prop="realName">
      </el-table-column>
      <el-table-column align="center" label="操作" width="200px">
        <template slot-scope="scope">
          <el-tooltip
            effect="dark"
            content="删除"
            placement="top"
            :enterable="false"
          >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.$index)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <span>共有{{ total }}条记录</span>
      <el-pagination
        background
        class="Repair_history_page"
        layout="prev, pager, next"
        :page-count="page_count"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <el-dialog :visible.sync="dialog" width="35%" class="award_dialog">
      <el-form
        label-width="100px"
        :model="dialog_from"
        @keyup.enter.native="dialog_confirm"
      >
        <el-form-item label="奖状名称:" :label-width="formLabelWidth">
          <el-input
            v-model="dialog_from.awardName"
            autocomplete="off"
            placeholder="请输入奖状名称..."
          ></el-input>
        </el-form-item>
        <el-form-item label="奖项等级:" :label-width="formLabelWidth">
          <el-select
            v-model="dialog_from.levelId"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.levelName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="颁发机构:" :label-width="formLabelWidth">
          <el-input
            v-model="dialog_from.issuer"
            autocomplete="off"
            placeholder="请输入颁发机构..."
          ></el-input>
        </el-form-item>

        <el-form-item label="获奖时间:" :label-width="formLabelWidth">
          <el-date-picker
            style="width: 100%"
            value-format="yyyy-MM-dd"
            ref="pickerRef"
            v-model="dialog_from.awardTime"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="奖状上传:" :label-width="formLabelWidth">
          <el-upload
            accept=".jpg,.jpeg,.png"
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-change="changeHandle"
            :auto-upload="false"
          >
            <img
              v-if="imgURL"
              :src="imgURL"
              class="avatar"
              style="width: 15rem"
            />

            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <p slot="tip" class="el-upload__tip" style="color: #909399">
              建议750*420，小于300kb，支持JPG、PNG格式
            </p>
          </el-upload>
        </el-form-item>
        <el-form-item label="证明材料:" :label-width="formLabelWidth">
          <el-upload
            accept=".jpg,.jpeg,.png"
            class="upload-demo"
            action="#"
            :on-change="change_file"
            :auto-upload="false"
            :file-list="fileList"
            :on-remove="handleRemove"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              请上传该奖状的所有证明材料...
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button type="primary" @click="dialog_confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5";
export default {
  props: {},
  components: {},
  data() {
    return {
      page: 1,
      page_count: 10,
      total: "xx",
      tableData: [],
      height: "",
      pageSize: 1,
      dialog: false,
      dialog_from: {
        awardName: "",
        levelId: "",
        issuer: "",
        awardTime: "",
        awardUrl: "",
        fileList: [],
      },
      time: "",
      options: [],
      formLabelWidth: "150px",
      // 图片文件
      imgFile: "",
      // 图片文件名称
      fileName: "",
      // 显示图片的地址
      imgURL: "",

      prove_file: [],
      // prove_fileName: "",
      fileList: [],
      percent: 0,
    };
  },
  methods: {
    handleCurrentChange(newSize) {
      this.page = newSize;
      this.get_award();
    },
    async get_award() {
      const self = this;
      const { data: res } = await this.$http({
        headers: { "Content-Type": "application/json;charset=UTF-8" },
        method: "get",
        url: "/api/usual/getAwardInfo",
        params: {
          page: self.page,
          pageSize: self.pageSize,
        },
      });

      this.page_count = res.msg.pages;
      this.total = res.msg.total;
      this.tableData = res.msg.records;
    },

    async removeUserById(index) {
      console.log(index);

      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //如果点确认的话，返回confirm
      //如果点取消的话，返回cancel

      console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      this.$message.success("删除成功");
      this.get_award();
    },
    getHeight() {
      // 获取浏览器高度，减去顶部导航栏的值70（可动态获取）,再减去head-DIV高度值80
      this.height = window.innerHeight;
      this.pageSize = parseInt((this.height * 0.61) / 131);
      this.get_award();
    },
    //j奖状上传
    async dialog_confirm() {
      this.uploadImg();
      this.upload_file();
      const self = this;

      this.dialog = false;
      this.imgURL = "";
      console.log(this.dialog_from.fileList);
      this.fileList = [];
    },
    changeHandle(file) {
      this.imgURL = URL.createObjectURL(file.raw);

      this.imgFile = file;
      this.fileName = file.name;

      // console.log(file);
    },
    async uploadImg() {
      // 创建COS实例  获取签名
      //这里写你们后端提供的请求接口即可，这里调用的接口是为了获取tmpSecretId、tmpSecretKey、sessionToken、expiredTime这些值
      const { data: res1 } = await this.$http({
        headers: { "Content-Type": "application/json;charset=UTF-8" },
        method: "get",
        url: "/api/upload/getSecretKey",
      });

      const data = res1.credentials;
      const cos = new COS({
        // 必选参数
        getAuthorization: (options, callback) => {
          const obj = {
            TmpSecretId: data.tmpSecretId,
            TmpSecretKey: data.tmpSecretKey,
            XCosSecurityToken: data.sessionToken,
            StartTime: res1.startTime, // 时间戳，单位秒，如：1580000000
            ExpiredTime: res1.expiredTime, // 时间戳，单位秒，如：1580000900
          };
          callback(obj);
        },
      });

      // 上传图片  其中Bucket 和 Region找你们负责人拿，Bucke和Region是由公司负责人使用公司账户，登入腾讯云，获取回来的。
      //key 在前面加上路径写法可以生成文件夹
      cos.putObject(
        {
          Bucket: "fuhuaqi-1311373154" /* 必须 */,
          Region: "ap-guangzhou" /* 存储桶所在地域，必须字段 */,
          Key: "/img/" + new Date().getTime() + this.fileName /* 必须 */,
          StorageClass: "STANDARD",
          Body: this.imgFile.raw, // 上传文件对象
          onProgress: (progressData) => {
            this.percent = progressData.percent * 100;
            // console.log(this.percent);
          },
        },
        (err, data) => {
          // 将上传后的封面进行路径拼接保存到本地

          const url = "https://" + data.Location;
          console.log(url);
          this.dialog_from.awardUrl = url;
        }
      );
    },

    async upload_file() {
      // 创建COS实例  获取签名
      //这里写你们后端提供的请求接口即可，这里调用的接口是为了获取tmpSecretId、tmpSecretKey、sessionToken、expiredTime这些值
      const { data: res1 } = await this.$http({
        headers: { "Content-Type": "application/json;charset=UTF-8" },
        method: "get",
        url: "/api/upload/getSecretKey",
      });

      const data = res1.credentials;
      const cos = new COS({
        // 必选参数
        getAuthorization: (options, callback) => {
          const obj = {
            TmpSecretId: data.tmpSecretId,
            TmpSecretKey: data.tmpSecretKey,
            XCosSecurityToken: data.sessionToken,
            StartTime: res1.startTime, // 时间戳，单位秒，如：1580000000
            ExpiredTime: res1.expiredTime, // 时间戳，单位秒，如：1580000900
          };
          callback(obj);
        },
      });

      for (let i = 0; i < this.prove_file.length; i++) {
        cos.putObject(
          {
            Bucket: "fuhuaqi-1311373154" /* 必须 */,
            Region: "ap-guangzhou" /* 存储桶所在地域，必须字段 */,
            Key:
              "/prove/" +
              new Date().getTime() +
              this.prove_file[i].name /* 必须 */,
            StorageClass: "STANDARD",
            Body: this.prove_file[i].raw, // 上传文件对象
            onProgress: (progressData) => {
              this.percent = progressData.percent * 100;
              // console.log(this.percent);
            },
          },
          async (err, data) => {
            // 将上传后的封面进行路径拼接保存到本地

            const url = "https://" + data.Location;
            console.log(url);

            const obj = {
              fileName: this.prove_file[i].name,
              url: url,
            };

            this.dialog_from.fileList.push(obj);

            if (this.prove_file.length == this.dialog_from.fileList.length) {
              const self = this;
              const { data: res } = await this.$http({
                headers: { "Content-Type": "application/json;charset=UTF-8" },
                method: "post",
                url: "/api/usual/addAwardInfo",
                data: self.dialog_from,
              });
              console.log(res);

              if (res.code != 200) {
                this.$message.error("上传失败");
              } else {
                this.$message.success(res.msg);
              }
              for (let i in this.dialog_from) {
                this.dialog_from[i] = "";
              }
              this.get_award();
            }
          }
        );
      }
      // 上传图片  其中Bucket 和 Region找你们负责人拿，Bucke和Region是由公司负责人使用公司账户，登入腾讯云，获取回来的。
      //key 在前面加上路径写法可以生成文件夹
    },

    change_file(file, fileList) {
      this.prove_file = fileList;
      console.log("添加");
      console.log(this.prove_file);
    },

    handleRemove(file, fileList) {
      this.prove_file = fileList;
      console.log("删除");
      console.log(this.prove_file);
    },
  },
  async created() {
    this.get_award();
    window.addEventListener("resize", this.getHeight); // 注册监听器
    this.getHeight(); // 页面创建时先调用一次

    const { data: res2 } = await this.$http({
      headers: { "Content-Type": "application/json;charset=UTF-8" },
      method: "get",
      url: "/api/usual/getAwardLevel",
    });
    this.options = res2.msg;
  },
  destroyed() {
    window.removeEventListener("resize", this.getHeight);
  },
};
</script>

<style lang="less">
.Award {
  display: flex;
  height: 90%;
  width: 90%;
  margin: auto;
  margin-top: 2%;
  box-shadow: 0 2px 14px rgba(0, 0, 0, 0.12), 0 0 10px rgba(0, 0, 0, 0.04);
  border-radius: 10px;
  border: 1px solid rgb(222, 222, 222);
  flex-direction: column;

  .el-table {
    margin: 20px;
    width: 98%;
    font-size: 17px;
  }
}

.Repair_history_page {
  height: 3%;
  width: 3%;
  display: flex;
  justify-content: end;
  margin: 0px 20px 00px 0px;
}

#button {
  background-color: rgb(53, 83, 137);
  margin: 10px 0px 10px 30px;

  color: #fff;

  font-size: 18px;

  display: flex;
}
.page {
  display: flex;

  justify-content: end;
  flex-direction: row-reverse;
  margin-bottom: 10px;
  span {
    width: 8%;
    margin: auto 0px;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 15rem;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.award_dialog {
  .el-form-item__label {
    text-align: center;
  }
}
</style>